//@login & register
const express=require('express');
const router=express.Router();
const bcrypt=require("bcryptjs");
const gravatar=require("gravatar");
const jwt=require('jsonwebtoken');
const passport=require("passport");

const User=require("../../models/User");
const keys=require("../../config/keys");

const saltRounds = 10;


//$route  Post api/users/register
//@desc   返回的请求的json数据
//@access public
router.post("/register",(req,res)=>{
    //查询数据库中是否拥有邮箱
    User.findOne({email:req.body.email})
    .then((user)=>{
        if(user)
        {
            return res.status(400).json("邮箱已被注册！")
        }
        else
        {
            let avatar = gravatar.url(req.body.email, {s: '200', r: 'pg', d: 'mm'});
            const newUser=new User({
                name:req.body.name,
                email:req.body.email,
                avatar:avatar,
                password:req.body.password,
                identity:req.body.identity
            })
            bcrypt.genSalt(saltRounds, function(err, salt) {
                bcrypt.hash(newUser.password, salt, (err, hash)=> {
                    if(err) throw err;
                    newUser.password=hash;
                    newUser.save()
                        .then(user=>res.json(user))
                        .catch(err=>console.log(err)); 
                });
            });
        }
    })
})

//$route  Post api/users/login
//@desc   返回的token jwt passport
//@access public
router.post("/login",(req,res)=>{
    // res.setHeader("Access-Control-Allow-Origin",'*');
    const email=req.body.email;
    const password=req.body.password;

    //查询数据库
    User.findOne({email})
    .then(user=>{
        if(!user){
            return res.status(404).json("用户不存在");
        }
        //密码匹配
        bcrypt.compare(password,user.password)
            .then(isMatch=>{
                if(isMatch){
                    const rule={
                        id:user.id,
                        name:user.name,
                        avatar:user.avatar,
                        identity:user.identity
                    };
                    //生成token
                    jwt.sign(rule,keys.secretOrKet,{expiresIn:36000},(err,token)=>{
                        if(err) throw err;
                        res.json({
                            success:true,
                            token:"Bearer "+token
                        });
                    })
                    
                }
                else{
                    return res.status(404).json("密码错误！");
                }
            })
    })
})

router.post("/getUser",(req,res)=>{
    User.findById(req.body.user)
    .then(user=>{
        res.json({
            id:user['_id'],
            name:user.name,
            avatar:user.avatar,
            identity:user.identity,
        })
    })
})

//$route  Get api/users/current
//@desc   return users
//@access private 请求第几页的用户
router.post("/getUsersByPage",passport.authenticate("jwt",{session:false}),(req,res)=>{
    if(req.user.identity=="管理员"){
        let page=req.body.page;
        User.find()
        .sort({'date':-1})
        .skip((page-1)*keys.admin_user_ereryPageCount)
        .limit(keys.admin_user_ereryPageCount)
        .then(users=>{
            res.json(users);
        })
    }
})

//获取用户数量并穿换成页数
router.post("/getUsersPageCount",passport.authenticate("jwt",{session:false}),(req,res)=>{
    if(req.user.identity=="管理员"){
        User.countDocuments()
        .then(count=>{
            if(count%keys.admin_user_ereryPageCount==0){
                res.send({'data':count/keys.admin_user_ereryPageCount});
            }
            else{
                let page=parseInt(count/keys.admin_user_ereryPageCount)+1;
                res.send({"data":page});
            }
        })
        
    }
})

//删除用户
router.post("/deleteUser",passport.authenticate("jwt",{session:false}),(req,res)=>{
    if(req.user.identity=="管理员"){
        User.deleteOne({'_id':req.body.user})
        .then(count=>{
            res.send({"data":"ok"});
        })
        .catch(err=>{
            res.send({"data":'err'});
        })
        
    }
})

module.exports=router;